import axios from 'axios'
import { ElMessage } from 'element-plus'

const service = axios.create({
  baseURL: 'http://localhost:8082',
  timeout: 10000
})

service.interceptors.request.use(
  config => {
    console.log('Request Config:', {
      url: config.url,
      method: config.method,
      params: config.params,
      data: config.data
    })
    return config
  },
  error => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    console.log('Response Status:', response.status)
    console.log('Response Headers:', response.headers)
    console.log('Response Data:', response.data)
    
    // 详细记录响应数据结构
    const res = response.data
    console.log('Response code:', res.code)
    console.log('Response message:', res.msg)
    console.log('Response data type:', typeof res.data)
    console.log('Response data value:', res.data)
    
    if (res.data && res.data.records) {
      console.log('Records length:', res.data.records.length)
      if (res.data.records.length > 0) {
        console.log('First record:', res.data.records[0])
      }
    }
    
    // 检查成功状态码 - 注意，后端返回的是code: 200而不是1
    if (res.code !== 200) {
      ElMessage.error(res.msg || '请求失败')
      return Promise.reject(new Error(res.msg || '请求失败'))
    }
    
    // 对于成功的响应，直接返回数据，不显示成功消息
    // 只有在某些特定操作成功时才应该显示成功消息，不是每次API调用都需要
    return res
  },
  error => {
    console.error('Response error:', error)
    if (error.response) {
      console.error('Error Status:', error.response.status)
      console.error('Error Data:', error.response.data)
    }
    ElMessage.error(error.message || '请求失败')
    return Promise.reject(error)
  }
)

export default service 